<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue'
import useIndexdb from '@/hooks/useIndexdb'
import uuid4 from 'uuid4'
import { dayjs } from 'element-plus'
import { longgangModeKey } from '@/utils/const'
import { cloneDeep } from 'lodash-es'

const emit = defineEmits(['current-session'])

export type Session = {
	uid: string // 唯一标识
	type: string // 会话模型的类型
	title: string // 标题
	time: string // 创建时间
	msgList: any[] // 聊天列表
}

const inputValue = ref('')
const editValue = ref('')
const sessionList = ref<Session[]>([])
const searchList = ref<Session[]>([])
const activeId= ref('')
const { getAllData, saveDataIdb, getDataByUid, deleteDataByUid, closeDatabase } = useIndexdb({
	databaseName: 'longgangSession',
	tableName: 'session',
})

// 切换会话
async function handleSwitchSession(item: Session) {
	let currentData = cloneDeep(item)
	console.log('切换会话', currentData)
	const data = await getDataByUid(item.uid)
	if (data) {
		currentData = JSON.parse(data.item.session)
	}
	activeId.value = currentData.uid
	emit('current-session', currentData)
}

// 编辑名称，确认 or 取消
function handleEdit(editData: any) {
	if (!editData) {
		// console.log('取消')
		bodyClick()
		return
	}
	const current: any = sessionList.value.find((o) => o.uid === editData.uid)
	if (editValue.value && current) {
		console.log(current, 'current')
		current.title = editValue.value
		saveDataIdb({ uid: current.uid, session: JSON.stringify(current) })
		handleSearch() // 编辑完成后，重新搜索
	}
	// console.log('编辑')
	bodyClick()
}

// 删除，确认 or 取消
function handleDel(delData: any) {
	if (!delData) {
		// console.log('取消')
		bodyClick()
		return
	}
	// console.log('删除')
	const index = sessionList.value.findIndex((o) => o.uid === delData.uid)
	if (delData && index > -1) {
		sessionList.value.splice(index, 1)
		deleteDataByUid(delData.uid)
	}

	// 如果删除了最后一个，需要新建一个
	if (!sessionList.value.length) {
		handleAddSession()
	} else {
		handleSwitchSession(sessionList.value[0])
	}
	bodyClick()
}

// 搜索
function handleSearch() {
	if (!inputValue.value) {
		searchList.value = []
		return
	}
	searchList.value = sessionList.value.filter((o) => o.title.includes(inputValue.value))
}

// 新建会话
async function handleAddSession() {
	console.log('新建')
	const cratedSession = {
		uid: uuid4(),
		title: '自定义助手',
		time: dayjs().format('HH:mm'),
		type: longgangModeKey.default,
		msgList: [],
	}
	sessionList.value.unshift(cratedSession)
	handleSwitchSession(cratedSession)
}

// 更新会话
function handleUpdateItem(item: Session) {
	console.log(item, 'item')
	sessionList.value = sessionList.value.map((o) => (o.uid === item.uid ? item : o))
	if (item) {
		saveDataIdb({ uid: item.uid, session: JSON.stringify(item) })
	}
}

defineExpose({
	onUpdateItem: handleUpdateItem,
})

function bodyClick() {
	document.body.click()
}

onMounted(() => {
	// 初始化indexdb数据
	getAllData().then((arr: any) => {
		if (arr.length) {
			arr.forEach((a: any) => {
				sessionList.value.unshift(JSON.parse(a.item.session))
			})
			handleSwitchSession(sessionList.value[0])
			// console.log(sessionList.value, '---------------', arr, 'arr')
		} else {
			// 需要初始化一条数据
			handleAddSession()
		}
	})
})
</script>
<template>
	<div class="left-side">
		<div class="head">
			<el-button type="primary" v-debounce:1000="handleAddSession">
				<el-icon><Plus /> </el-icon>
				新建
			</el-button>
		</div>
		<div class="search">
			<el-input v-model="inputValue" placeholder="请输入搜索内容" clearable @input="handleSearch">
				<template #prefix>
					<el-icon>
						<search />
					</el-icon>
				</template>
			</el-input>
		</div>
		<div class="session-list">
			<!-- [inputValue?...searchList:...searchList] -->
			<div
				class="item"
				:class="o.uid === activeId? 'active' : ''"
				:title="o.uid"
				@click="handleSwitchSession(o)"
				v-for="o in inputValue ? searchList : sessionList"
			>
				<p class="text one-line">{{ o.title }}</p>
				<time>{{ o.time }}</time>
				<div class="operate">
					<el-popover
						trigger="click"
						popper-class="longgang-chat-session-item"
						placement="right-start"
						width="300"
						@show="editValue = o.title"
						@hide="editValue = ''"
					>
						<template #reference>
							<el-icon :size="18">
								<Edit />
							</el-icon>
						</template>
						<div class="edit-form">
							<h6>重命名</h6>
							<el-input
								v-model="editValue"
								placeholder="请输入名称"
								clearable
								maxlength="20"
								show-word-limit
							></el-input>
							<div class="button">
								<el-button type="default" @click="handleEdit(null)">取消</el-button>
								<el-button type="primary" @click="handleEdit(o)">确定</el-button>
							</div>
						</div>
					</el-popover>
					<el-popover trigger="click" popper-class="longgang-chat-session-item" placement="right-start" width="300">
						<template #reference>
							<el-icon :size="18" class="delete-icon">
								<Delete />
							</el-icon>
						</template>
						<div class="delete-side">
							<h6>删除会话</h6>
							<p class="tip-max">本条会话数据将被永久删除，不可恢复及撤销。确定要删除吗？</p>
							<div class="button">
								<el-button type="default" @click="handleDel(null)">取消</el-button>
								<el-button type="danger" @click="handleDel(o)">确定</el-button>
							</div>
						</div>
					</el-popover>
				</div>
			</div>
		</div>
	</div>
</template>
<style lang="scss" scoped>
.left-side {
	padding: 0 14px;
	overflow-y: hidden;
	.head {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 68px;
		img {
			width: 180px;
		}
		button {
			width: 100%;
			.el-icon {
				margin-right: 6px;
				font-size: 16px;
				svg {
				}
			}
		}
	}
	.session-list {
		height: calc(100vh - 110px);
		margin-top: 10px;
		padding: 0px 0 20px;
		overflow-y: auto;
		.item {
			display: flex;
			align-items: center;
			white-space: nowrap;
			text-overflow: ellipsis;
			overflow: hidden;
			justify-content: space-between;
			color: #000;
			height: 42px;
			margin-top: 8px;
			padding: 0 14px;
			cursor: pointer;
			position: relative;
			transition: all 0.15s;
			border-radius: 6px;
			&:hover,
			&.active {
				background-color: #f6f7fb;
				.operate {
					opacity: 1;
				}
			}
			.text {
				font-size: 14px;
				padding-right: 20px;
			}
			.operate {
				opacity: 0;
				position: absolute;
				right: 14px;
				top: 50%;
				transform: translate(0, -50%);
				transition: all 0.15s;
				background: #f6f7fb;
				display: flex;
				justify-content: flex-end;
				.el-tooltip__trigger {
					margin-left: 10px;
					&.delete-icon {
						color: red;
					}
				}
			}
		}
	}
}
</style>
<style lang="scss">
// 编辑和删除 el-popover
.longgang-chat-session-item {
	.edit-form,
	.delete-side {
		h6 {
			font-size: 16px;
			font-weight: 600;
		}
		.el-input {
			margin: 10px 0;
		}
		.tip-max {
			font-size: 14px;
			line-height: 20px;
			color: #999999;
			margin: 10px 0;
		}
		.button {
			display: flex;
			justify-content: flex-end;
			margin-top: 14px;
		}
	}
	.delete-side {
	}
}
</style>
